//
//  WBComposeController.swift
//  WeiboTen
//
//  Created by ItHeiMa on 2017/7/16.
//  Copyright © 2017年 itHeima. All rights reserved.
//

import UIKit

fileprivate let identifier = "identifier"
fileprivate let maxpicCount = 7

class WBComposeController: UIViewController {
    /// 默认是系统键盘
    var isDefalutKeyboard: Bool = true
    
    /// toolBar是否执行动画
    var isAnimation: Bool = true
    
    var selectedIndex: Int = 0
    /// 数据源数组
    var images: [UIImage] = []
    
    lazy var textView: WBTextView = WBTextView()
    
    lazy var tooBar: UIToolbar = UIToolbar() //默认44
    
    lazy var composeButton: UIButton = UIButton(text: "发布", titleColor: UIColor.white, bgImage: "new_feature_finish_button", target: self, selector: #selector(compose))
    
    lazy var pictureView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        
        let height = (screenWidth - 48.0)/3
        //每个子item的大小
        layout.itemSize = CGSize(width: height, height: height)
        //每行和每列的间隔
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 12
        //滚动方向垂直，布局方向是水平
        layout.scrollDirection = .vertical
        let rect = CGRect(x: 12, y: 120, width: screenWidth-24, height: screenWidth-24)
        let collectionView = UICollectionView(frame: rect, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.yellow
        
        collectionView.dataSource = self
        collectionView.register(WBComposeCell.self, forCellWithReuseIdentifier: identifier)
        
        return collectionView
    }()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        //接收键盘的frame将要变化的通知
        let notification = UIResponder.keyboardWillChangeFrameNotification
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChange(notification:)), name: notification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(addOrDeleteEmotion(notification:)), name: emotionButtonClickNotification, object: nil)
        
        setupUI()
    }
}

extension WBComposeController {
    func setupUI () {
        //设置导航条
        setupNavigationBar()
        
        //设置textView
        setupTextView()
        
        //设置底部的toolBar
        setupToolBar()
        
        //设置pictureView
        setupPictureView()
    }
    
    func setupNavigationBar() {
        //1. 设置返回按钮
        let backButton = UIButton(text: "取消", titleColor: UIColor.white, bgImage: "new_feature_finish_button", target: self, selector: #selector(back))
        backButton.frame = CGRect(x: 0, y: 0, width: 50, height: 30)
        let leftItem = UIBarButtonItem(customView: backButton)
        self.navigationItem.leftBarButtonItem = leftItem
        
        //2. 设置发布按钮
        composeButton.frame = CGRect(x: 0, y: 0, width: 50, height: 30)
        
        //当button的状态是不能点击状态
        composeButton.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        composeButton.setTitleColor(UIColor.gray, for: .disabled)
        let rightItem = UIBarButtonItem(customView: composeButton)
        self.navigationItem.rightBarButtonItem = rightItem
        
        //如果要设置button的isEnabled的属性并让其生效，必须等到将其添加取父视图之后
        composeButton.isEnabled = false
        
        //3. 设置title
        let titleView = UILabel()
        titleView.numberOfLines = 0
        titleView.textAlignment = .center
        
        //生成title的富文本， 富文本就是有多种样式的文本组合体
        let attriButtedStr = NSMutableAttributedString(string: "发布微博\n", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.black])
        
        
        //testDebug
        //"test":WBUserAccount.shared.screen_name!
        let nameStr = NSAttributedString(string: "test", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12), NSAttributedString.Key.foregroundColor: UIColor.lightGray])
        
        attriButtedStr.append(nameStr)
        titleView.attributedText = attriButtedStr
        navigationItem.titleView = titleView
        titleView.sizeToFit()
    }
    
    func setupTextView() {
        //创建并设置textView
        
        textView.delegate = self
        //textView.delegate = self
        textView.font = UIFont.systemFont(ofSize:  18)
        textView.backgroundColor = UIColor.white
        textView.placeHolder = "请你发微博"

        self.view.addSubview(textView)
        
        textView.snp.makeConstraints { (make) in
            make.top.left.right.bottom.equalTo(self.view)
        }
    }
    
    func setupToolBar() {
        
        self.view.addSubview(tooBar)
        tooBar.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
        }
        var items: [UIBarButtonItem] = []
        
        let paramDicArr: [[String: Any]] = [["image":"compose_mentionbutton_background", "selector": #selector(compose)],
                                          ["image":"compose_trendbutton_background", "selector": #selector(compose)],
                                          ["image":"compose_camerabutton_background", "selector": #selector(compose)],
                                            ["image":"compose_emoticonbutton_background", "selector": #selector(toggleKeyboard)],
                                            ["image":"compose_keyboardbutton_background", "selector": #selector(toggleKeyboard)]]
        for i in 0..<5 {
            let image = paramDicArr[i]["image"] as! String
            let selector = paramDicArr[i]["selector"] as! Selector
            let button = UIButton(text: nil, image: image, target: self, selector: selector)
            let item = UIBarButtonItem(customView: button)
            //弹簧
            let flexbleItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
            
            //button自适应大小
            button.sizeToFit()
            
            items.append(item)
            items.append(flexbleItem)
        }
        //删除多余的弹簧
        items.removeLast()
        
        tooBar.items = items
    }
    
    func setupPictureView() {
        textView.addSubview(pictureView)
    }
}

// MARK: - 事件处理
extension WBComposeController {
    @objc func back() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc func compose() {
    
    }
    
    
    /// 点击表情键盘的通知处理
    ///
    /// - Parameter notification: notification
    @objc func addOrDeleteEmotion(notification: Notification) {
        if let userInfo = notification.userInfo, let isDelete = userInfo["isDelete"] as? Bool {
            if isDelete {
                textView.deleteBackward()
            } else {
                let model = userInfo["model"] as! WBEmotionModel
                textView.insertEmotion(emotion: model)
            }
        }
    }
    
    /// 键盘的frame将要变化时的通知
    @objc func keyboardChange(notification: Notification) {
        if isAnimation {
            //print(notification)
            //1. 取到键盘弹出后的frame
            if let keyBoardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
                let rect = keyBoardFrame.cgRectValue
                //计算出toolBar的底部约束
                let bottomOffset = rect.origin.y - screenHeight
                
                //只是修改约束的值，约束的值并不会立刻生效
                self.tooBar.snp.updateConstraints({ (make) in
                    make.bottom.equalTo(self.view).offset(bottomOffset)
                })
                
                UIView.animate(withDuration: 0.25, animations: {
                    //让约束生效
                    self.view.layoutIfNeeded()
                })
            }
        }
    }
    
    
    /// 切换键盘
    @objc func toggleKeyboard() {
        //将系统的键盘隐藏
        //所有的文本输入框都有两个方法
        //becomeFristResponder: 成为第一响应者，就意味着光标定位到该输入控件上，此时键盘自动弹起
        //resignFirstResponder: 收起键盘
        //先把当前的键盘收起
        
        isAnimation = false
        textView.resignFirstResponder()
        isAnimation = true
        
        if isDefalutKeyboard {
            //自定义一个view，作为自定义键盘
            let mykeyboard = WBKeyboard(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 271))
            //mykeyboard.backgroundColor = UIColor.red
            
            //设置textView的inputView
            textView.inputView = mykeyboard
            isDefalutKeyboard = false
        } else {
            //收起自定义键盘
            textView.inputView = nil
            //弹出系统键盘
            isDefalutKeyboard = true
        }
        
        //把需要展示的键盘弹出
        textView.becomeFirstResponder()
    }
}

extension WBComposeController: UITextViewDelegate {
    /// textView的文字长度发生变化时调用
    func textViewDidChange(_ textView: UITextView) {
        composeButton.isEnabled = textView.text.count > 0
    }
}

extension WBComposeController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //如果没有达到最大图片张数，就返回图片张数加1个cell。否则就返回图片张数个cell
        return images.count == maxpicCount ? maxpicCount : images.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! WBComposeCell
        cell.delegate = self
        //说明是加号按钮
        if indexPath.item == images.count {
            cell.image = nil
        } else {
            cell.image = images[indexPath.item]
        }
        
        cell.backgroundColor = UIColor.red
        
        return cell
    }
}

extension WBComposeController: WBComposeCellDelegate {
    func addOrChangeImage(cell: WBComposeCell) {
        //根据cell取到index
        let indexPath = pictureView.indexPath(for: cell)
        selectedIndex = (indexPath?.item)!
        
        //选择图片的控制器
        let photoController = UIImagePickerController()
        photoController.delegate = self
        present(photoController, animated: true, completion: nil)
    }
    
    
    func deleteImage(cell: WBComposeCell) {
        //根据cell取到index
        let indexPath = pictureView.indexPath(for: cell)
        let index = (indexPath?.item)!
        images.remove(at: index)
        
        pictureView.reloadData()
    }
}


// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate, 在使用imagePicker时，必须同时遵循以上两个代理，但只需要实现UIImagePickerControllerDelegate
extension WBComposeController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerController.InfoKey.originalImage.rawValue] as! UIImage
        let littleImage = image.compressImage(size: CGSize(width:100, height:100))
        
        //取到图片二进制数据的字节数，想得到有多个M， （/1024/1024）
        let imageSize = Double((image.pngData()?.count)!) //取到data的字节数
        let limageSize = Double((littleImage!.pngData()?.count)!)
        
        let beisu = String(format: "%02f", imageSize/limageSize)
        //print("大图比小图：\(beisu)")
        
        //通过index来判断点击的是替换还是添加
        if selectedIndex == images.count {
            //点击的是加号按钮
            images.append(littleImage!)
        } else {
            //替换图片
            images[selectedIndex] = littleImage!
        }

        pictureView.reloadData()
        
        dismiss(animated: true, completion: nil)
    }
}



